package mina;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.SocketSessionConfig;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

public class MinaServer {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        NioSocketAcceptor acceptor = new NioSocketAcceptor();
        SocketSessionConfig conf = acceptor.getSessionConfig();
        conf.setBothIdleTime(1000);
        conf.setReadBufferSize(1024 * 8);
        conf.setIdleTime(IdleStatus.BOTH_IDLE, 10);
        //设置日志记录器
        DefaultIoFilterChainBuilder filter = acceptor.getFilterChain();
        filter.addLast("logger", new LoggingFilter());
        //设置编码过滤器
        filter.addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(StandardCharsets.UTF_8)));
        // 指定业务逻辑处理器
        acceptor.setHandler(new MyIOHandler());
        // 设置端口号
        acceptor.bind(new InetSocketAddress(8787));
        // 启动监听线程
        acceptor.bind();
        System.out.println("服务器启动,端口:8787");
    }

    static class MyIOHandler extends IoHandlerAdapter {
        /**
         * 当一个新客户端连接后触发此方法
         */
        @Override
        public void sessionCreated(IoSession session) throws Exception {
            // 显示客户端的ip和端口
            System.out.println(session.getRemoteAddress().toString());
        }

        /**
         * 当接收到客户端的请求信息后触发此方法
         */
        @Override
        public void messageReceived(IoSession session, Object message) throws Exception {
            String strMsg = message.toString();
            if (strMsg.trim().equalsIgnoreCase("quit")) {
                session.closeNow();
                return;
            }
            // 返回消息字符串
            session.write("Hi Client!");
            // 打印客户端传来的消息内容
            System.out.println("Message written : " + strMsg);
        }

        /**
         * 当信息已经传送给客户端后触发此方法
         */
        @Override
        public void messageSent(IoSession session, Object message) throws Exception {
            // 返回消息字符串
            System.out.println("信息传送到客户端。");
        }

        /**
         * 当连接空闲时触发此方法
         */
        @Override
        public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
            System.out.println("IDLE" + session.getIdleCount(status));
        }
    }
}
